Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath({'Ext.ux' : 'extjs4/ux'});
Ext.define('TS.view.rp.RpPayBillEditor',{
	extend: 'Ext.form.Panel',
	border: false,
	bodyPadding:0,
	layout:'anchor',
	alias: 'widget.rppaybilleditor',
	title: '付款单-新增',
	bill:null,
	constructor:function(config) {
		var me = this;
		this.initConfig(config);
		if(config.bill) {
			this.bill = config.bill;
		}
		me.self.superclass.constructor.call(this,config);
	},
	initComponent:function() {
		//初始化业务员列表
		var store = Ext.create('TS.store.base.EmpStore');
		var invComp = Ext.ComponentQuery.query('accmenu combobox')[0];
		var invModel = invComp.findRecordByValue(invComp.getValue());
		var deptId = invModel.get('deptId');
		store.load({params:{deptId:deptId}});		
		//创建应付金额验证器
		var unzerovalid = Ext.apply(Ext.form.field.VTypes,{
			unzero:function(value,field) {
				return value != 0;
			},
			unzeroText:'金额不能为零!',
			negative:function(value,field) {
				return value < 0;
			},
			negativeText:'退款单金额必须是负数',
			zero:function(value,field) {
				return value == 0;
			},
			zeroText:'退款单折扣必须是零',
			positive:function(value,field) {
				return value > 0;
			},
			positiveText:'付款单金额必须是正数'
		});		
		var billTypeStore = Ext.create('Ext.data.Store',{
			fields:['key','value'],
			data : [
			   {key:-1,value:'付款单'},
			   {key:-2,value:'预付单'},
			   {key:-3,value:'退款单'}
			]
		});
		
	    var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
	    	clicksToEdit: 1,
	    	listeners:{
	    		'edit':function(editor, e) {
	    			if(e.column.dataIndex == "discount") {
	    				var billAmount = e.record.getarpBill().get('amount');
	    				var settleAmount = billAmount - e.value;
	    				e.record.set('settleAmount',settleAmount);
	    			}
	    			e.grid.getStore().commitChanges();
	    			e.grid.getView().refresh();
	    			this.onUpdateBillAmount(e.grid);
	    		},
	    		scope:this
	    	}
	    });		
		this.items = [
       		    {
    		    	xtype: 'fieldset',
    	            title: '基本信息',
    	            anchor:'100% 25%',
    	            minHeight:140,
                    defaults: {
                        labelWidth: 89,
                        anchor: '100%',
                        layout: {
                            type: 'hbox',
                            defaultMargins: {top: 0, right: 5, bottom: 0, left: 0}
                        }
                    },
                    items:[
    	                   {
    	                	   xtype:'fieldcontainer',
    	                	   items:[
    	                	          {
    	          		    	    	xtype: 'triggerfield',
    	        		    	    	emptyText:'请输入客户编码或名称',
    	        		    	    	trigger1Cls:Ext.baseCSSPrefix + 'form-search-trigger',
    	        		    	    	onTriggerClick:function(e){e.keyCode=e.ENTER;this.fireEvent('specialkey',this,e);},
    	        		            	name: 'customerCode',
     	        		            	fieldLabel: '客户编码',
    	        		            	labelStyle:'text-align:right',
    	        		            	allowBlank:false,
    	        		            	listeners: {
    	        		            		specialkey:function(field,e) {
    	        		            			//var custIdField = field.up('form').down('hiddenfield[name=customerId]');
    	        		            			if(e.getKey() == e.ENTER && field.value != '') {
    	        		            			    	var view=Ext.create('TS.view.base.CustomerSearchDialog');
    	        		            			    	view.setVal(field.value);
    	        		            			    	view.on({
    	        		            					    selected: function(records){
    	        		            					    	if(records.length == 0) {
    	        		            					    		Ext.MessageBox.alert('ThinkGsp','未检索到任何客户信息!');
    	        		            					    	} else {
    	        		            						    	field.setValue(records[0].get('customerCode'));
    	        		            						    	var nameField = field.up('form').down('textfield[name=customerName]');
    	        		            						    	nameField.setValue(records[0].get('customerName'));
    	        		            						    	var form = field.up('form');
    	        		            						    	form.getRecord().setcustomer(records[0]);
    	        		            						    	form.getRecord().set('custSuppId',records[0].get('customerId'));
    	        		            					    	}
    	        		            					    },
    	        		            					    scope: this
    	        		            					});
    	        		            			    	view.show();	
    	        		            		    }        			
    	        		            		}
    	        		            	}
    	                	          },
    	                	          {
    	          		            	xtype: 'textfield',
    	        		            	readOnly:true,
    	        		            	width:512,
    	        		            	name: 'customerName',
    	        		            	labelStyle:'text-align:right',
    	        		            	fieldLabel: '客户名称',
    	        		            	allowBlank:false
    	                	          }
    	                	   ]
    	                   },
    	                   {
    	                	   xtype:'fieldcontainer',
    	                	   items:[
    	                	          { 
    	                	        	xtype:'combobox',
    	          		        		fieldLabel: '部门',
    	                                labelStyle:'text-align:right',
    	                                name:'deptName',
    	        		        		allowBlank:false
    	                	          },
    	                	          {
    	                	        	  xtype:'textfield',
    	                	        	  fieldLabel:'单据编号',
    	                	        	  labelStyle:'text-align:right',
    	                	        	  name:'rpBillCode',
    	                	        	  allowBlank:false
    	                	          },
    	                	          {
    	                	        	  xtype:'combobox',
    	                	        	  fieldLabel:'单据类型',
      	                                  labelStyle:'text-align:right',
      	                                  name:'rpBillType',
    	                	        	  allowBlank:false,
    	                	        	  store:billTypeStore,
    	                	        	  displayField:'value',
    	                	        	  valueField:'key',
    	          						  forceSelection:true,
    	        						  typeAhead : true,
    	        						  listeners:{
    	        								select:function(combo,records) {
    	        									var model = this.up('form').getRecord();
    	        									model.set('rpBillName',records[0].get('value'));
    	        									
    	        									amountField = combo.up('form').down('numberfield[name=amount]');
    	        									discountField = combo.up('form').down('numberfield[name=discount]');
    	        									var key = records[0].get('key');
    	        									switch(key) {
    	        									case -1:
    	        										amountField.vtype = 'positive';
    	        										break;
    	        									case -2:
    	        										amountField.vtype = 'positive';
    	        										break;
    	        									case -3:
    	        										amountField.vtype = 'negative';
    	        										discountField.vtype = 'zero';
    	        										break;
    	        									}
    	        								}
    	        							}
    	                	          }
    	                	   ]
    	                   },
    	                   {
    	                	   xtype:'fieldcontainer',
    	                	   items:[
    	                	          { 
      	                	        	xtype:'combobox',
      	          		        		fieldLabel: '业务员',
      	        		        		name:'empId',
      	        		        		store:store,
    	                                labelStyle:'text-align:right',
    	                                allowBlank:false,
    	                                displayField:'empName',
    	                                valueField:'empId',
    	        						forceSelection:true,
    	        						typeAhead : true,
    	        						listeners:{
    	        							select:function(combo,records) {
    	        								var model = this.up('form').getRecord();
    	        								model.setemp(records[0]);
    	        							}
    	        						}
      	                	          },
      	                	          {
      	                	        	  xtype:'numberfield',
      	                	        	  name:'amount',
      	                	        	  allowBlank:false,
      	                	        	  labelStyle:'text-align:right',
      	                	        	  fieldStyle:'text-align:right',
      	                	        	  allowDecimals: true,
     	                	        	  fieldLabel:'付款金额',
    	                	        	  hideTrigger: true,
    	                	              keyNavEnabled: false,
    	                	              mouseWheelEnabled: false,
    	                	              allowDecimals: true,
     	                	        	  vtype:'positive'
      	                	          },
      	                	          {
      	                	        	  xtype:'datefield',
      	                	        	  name:'billDate',
      	                	        	  labelStyle:'text-align:right',
      	                	        	  fieldLabel:'单据日期',
      	                	        	  allowBlank:false,
      	                	        	  format:'Y-m-d',
      	                	          }
    	                	   ]
    	                   },
    	                   {
    	                	   xtype:'fieldcontainer',
    	                	   items:[
    	                	          {
	    	      		        		xtype:'textfield',
	    	    		        		readOnly:true,
	    	    		        		labelStyle:'text-align:right',
	    	    		        		fieldLabel:'制单人',
	    	    		        		name:'makerName',
	    	    		        		allowBlank:false
    	                	          },
    	                	          {
    	                	        	  xtype:'numberfield',
    	                	        	  name:'discount',
    	                	        	  hideTrigger:true,
      	                                  labelStyle:'text-align:right',
      	                	        	  fieldStyle:'text-align:right',
    	                	        	  allowBlank:false,
    	                	        	  fieldLabel:'折扣金额',
    	                	        	  minValue: 0,
    	                	        	  hideTrigger: true,
    	                	              keyNavEnabled: false,
    	                	              mouseWheelEnabled: false,
    	                	              allowDecimals: true
    	                	          },
    	                	          {
    	                	        	  xtype:'textfield',
    	                	        	  fieldLabel:'备注',
      	                                  labelStyle:'text-align:right',
    	                	        	  name:'remark'
    	                	          }
    	                	   ]
    	                   }
    	            ]
    		    },
    		    {
    		    	xtype:'grid',
    				header:false,
    				border:false,
    				region:'center',
    				anchor:'100% 75%',
    			    features: [{
    			        ftype: 'summary'
    			    }],
				    plugins: [
				              cellEditing
			        ],
    				columns:[
							 {
							    xtype: 'actioncolumn',
							    width: 30,
							    sortable: false,
							    menuDisabled: true,
							    items: [{
							        iconCls: 'action-delete',
							        tooltip: '删除',
							        scope: this,
							        handler: this.onRemoveClick
							    }]
							 },
    				         {header:'单据类型',dataIndex:'arpBill',summaryType:'count',summaryRenderer: function(value, summaryData, dataIndex) {return '<b>' + Ext.String.format('合计[{0}]:', value) + '</b>'; },renderer:function(value,metaData,record){return record.getarpBill().get('arpBillName');}},
    				         {header:'单据日期',renderer:function(value,metaData,record){return Ext.util.Format.date(record.getarpBill().get('billDate'),'Y-m-d');}},
    				         {header:'单据编号',renderer:function(value,metaData,record){return record.getarpBill().get('arpBillCode');}},
    				         {header:'应付金额',renderer:function(value,metaData,record){return record.getarpBill().get('amount');}},
    				         {
    				        	 header:'结算金额',dataIndex:'settleAmount',align:'right',
    				        	 summaryType:'sum',summaryRenderer:function(value,summaryData,dataIndex){return '<b>' + Ext.util.Format.number(value,'0,000.00') + '</b>';},
    				        	 renderer : Ext.util.Format.numberRenderer('0.00'),
	 				             editor: {
					                    xtype: 'numberfield',
					                    allowBlank: false,
		                	        	fieldStyle:'text-align:right',
		                	        	allowDecimals: true
					             }
    				         },
    				         {
    				        	 header:'折扣金额',dataIndex:'discount',align:'right',
    				        	 summaryType:'sum',summaryRenderer:function(value,summaryData,dataIndex){return '<b>' + Ext.util.Format.number(value,'0,000.00') + '</b>';},
    				        	 renderer : Ext.util.Format.numberRenderer('0.00'),
	 				             editor: {
					                    xtype: 'numberfield',
					                    allowBlank: false,
		                	        	fieldStyle:'text-align:right',
		                	        	allowDecimals: true
					             }
    				         },
    				         {
    				        	 header:'备注',dataIndex:'remark',width:200,
	 				             editor: {
					                    xtype: 'textfield'
					             }    				        	 
    				         }
    				]
    		    }	       
		];
    	this.tbar=[
    	      	{xtype:'button',text:'保存',action:'saveBill',iconCls:'button-save'},
    			{xtype:'button',text:'归档',action:'archiveBill',iconCls:'bill-archive-button'},
    			{xtype:'button',text:'反归档',action:'unArchiveBill',iconCls:'bill-unarchive-button'},
    			{xtype:'button',text:'自动核销',action:'autoCheckBill',iconCls:'button-autocheck'},
    			{xtype:'button',text:'打印',action:'printBill',iconCls:'bill-printer-button'},
    			{xtype:'button',text:'应付单',action:'refAPayBill',iconCls:'button-arpbill-link'}
    	],
		this.callParent(arguments);
		if(!this.bill) {
			var store = Ext.create('Ext.data.Store',{
				model: 'TS.model.rp.RpBillModel',
				proxy:{
					url:'rp/paybill/createPayBill.do',
					type:'ajax',
					reader:{
						type:'json',
						root:''
					}
				},
				autoLoad:false
			});
			store.load({
				callback:function(records, operation, success) {
					this.bill = records[0];
					this.loadRecord(this.bill);
					this.initAssociation(this.bill);
				},
				scope:this
			});
		} else {
			this.loadRecord(this.bill);
			this.initAssociation(this.bill);
		}
	},
	
	//初始化Combobox
    initAssociation: function(model) {
    	var deptField = this.down('combobox[name=deptName]');
    	deptField.setValue(model.getdept().get('deptName'));
    	var empField = this.down('combobox[name=empId]');
    	empField.select(model.getemp().get('empId'));
    	var makerField = this.down('textfield[name=makerName]');
    	makerField.setValue(model.getmaker().get('empName'));
    	if(model.customerHasOneInstance != null) {
    		this.down('triggerfield').setValue(model.getcustomer().get('customerCode'));
    		this.down('textfield[name=customerName]').setValue(model.getcustomer().get('customerName'));
    	}
    	var billTypeField = this.down('combobox[name=rpBillType]');
    	billTypeField.setValue(model.get('rpBillType'));
    	this.down('grid').reconfigure(model.details());
    	this.onUpdateState(this,model);
     },
     onRemoveClick: function(gridView, rowIndex){
    	 gridView.getStore().removeAt(rowIndex);
    	 gridView.refresh();
    	 this.onUpdateBillAmount(gridView.up());
     },
     //刷新单据主体的结算金额
     onUpdateBillAmount:function(grid) {
    	 var store = grid.getStore();
		 var sumSettle = store.sum('settleAmount');
		 var sumDiscount = store.sum('discount');
		 var amountField = grid.up('form').down('fieldset').down('numberfield[name=amount]');
		 var disField = grid.up('form').down('numberfield[name=discount]');
		 amountField.setValue(sumSettle);
		 disField.setValue(sumDiscount);
     },
     onUpdateState:function(form,bill) {
    	 if(bill.get('archived')) {
    		 form.down('button[action=archiveBill]').setDisabled(true);
    		 form.down('button[action=saveBill]').setDisabled(true);
    		 form.down('button[action=refAPayBill]').setDisabled(true);
    		 form.down('button[action=unArchiveBill]').setDisabled(false);
    		 form.down('button[action=autoCheckBill]').setDisabled(false);
    	 } else {
    		 form.down('button[action=saveBill]').setDisabled(false);
    		 form.down('button[action=archiveBill]').setDisabled(false);
    		 form.down('button[action=unArchiveBill]').setDisabled(true);
    		 form.down('button[action=refAPayBill]').setDisabled(false);
    		 form.down('button[action=autoCheckBill]').setDisabled(true);
    	 }
    	 if(bill.get('checkAmount') > 0 || bill.get('checkStatus') > 0) {
    		 form.down('button[action=unArchiveBill]').setDisabled(true);
    		 form.down('button[action=autoCheckBill]').setDisabled(true);
    	 }
    	 if(bill.get('rpBillId') == 0) {
    		 this.setTitle('付款单-新增');
    	 } else if(this.bill.get('archived')) {
			 this.setTitle('付款单-查看');
		 } else {
			 this.setTitle('付款单-编辑');
		 }
     },
});